import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { authService, type UserInfo, type LoginDto } from '../services/auth.service';
import { storage, StorageKey } from '~/utils/storage';
import { useRouteStore } from './route.store';

/**
 * 认证状态
 */
interface AuthState {
  // 状态
  token: string | null;
  userInfo: UserInfo | null;
  isAuthenticated: boolean;
  permissions: string[];

  // 操作
  login: (data: LoginDto) => Promise<void>;
  logout: () => Promise<void>;
  initialize: () => Promise<void>;
  setToken: (token: string) => void;
  setUserInfo: (userInfo: UserInfo) => void;
  fetchUserInfo: () => Promise<void>;
  clearAuth: () => void;
}

/**
 * 认证 Store
 */
export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      // 初始状态
      token: null,
      userInfo: null,
      isAuthenticated: false,
      permissions: [],

      // 登录
      login: async (data: LoginDto) => {
        const response = await authService.login(data);
        const { accessToken, user } = response;

        // 保存 token 到 storage
        storage.set(StorageKey.AUTH_TOKEN, accessToken);
        storage.set(StorageKey.USER_INFO, user);

        // 保存权限到 storage（从登录响应中获取，无需额外请求）
        if (user.permissions) {
          storage.set(StorageKey.USER_PERMISSIONS, user.permissions);
        }

        // 更新状态
        set({
          token: accessToken,
          userInfo: user,
          isAuthenticated: true,
          permissions: user.permissions || [],  // 直接使用登录响应中的权限
        });

        // 登录成功后加载用户菜单（权限已从登录响应中获取）
        try {
          await useRouteStore.getState().loadMenus();
        } catch (error) {
          console.error('加载菜单失败:', error);
        }
      },

      // 登出
      logout: async () => {
        try {
          // 调用后端登出接口，将 token 加入黑名单
          await authService.logout();
        } catch (error) {
          console.error('登出失败:', error);
          // 即使后端登出失败，也要清除前端状态
        } finally {
          // 清除前端状态
          get().clearAuth();
        }
      },

      // 初始化认证状态（应用启动时调用）
      initialize: async () => {
        // 如果已经认证，跳过初始化（避免重复请求）
        if (get().isAuthenticated) {
          return;
        }

        const token = storage.get<string>(StorageKey.AUTH_TOKEN);
        const userInfo = storage.get<UserInfo>(StorageKey.USER_INFO);
        const permissions = storage.get<string[]>(StorageKey.USER_PERMISSIONS);

        if (token && userInfo) {
          // 验证 token 有效性
          try {
            // 尝试获取用户信息，验证 token 是否有效
            const freshUserInfo = await authService.getProfile();
            set({
              token,
              userInfo: freshUserInfo,
              isAuthenticated: true,
              permissions: freshUserInfo.permissions || permissions || [],  // 优先使用最新的权限
            });
          } catch (error) {
            // Token 无效，清除状态
            console.error('Token 验证失败:', error);
            get().clearAuth();
          }
        } else {
          // 没有 token，确保状态已清除
          get().clearAuth();
        }
      },

      // 设置 token
      setToken: (token: string) => {
        storage.set(StorageKey.AUTH_TOKEN, token);
        set({ token, isAuthenticated: true });
      },

      // 设置用户信息
      setUserInfo: (userInfo: UserInfo) => {
        storage.set(StorageKey.USER_INFO, userInfo);
        set({ userInfo });
      },

      // 获取用户信息
      fetchUserInfo: async () => {
        const userInfo = await authService.getProfile();
        storage.set(StorageKey.USER_INFO, userInfo);
        set({ userInfo });
      },

      // 清除认证状态
      clearAuth: () => {
        storage.remove(StorageKey.AUTH_TOKEN);
        storage.remove(StorageKey.USER_INFO);
        storage.remove(StorageKey.USER_PERMISSIONS);
        set({
          token: null,
          userInfo: null,
          isAuthenticated: false,
          permissions: [],
        });
        // 清除菜单缓存
        useRouteStore.getState().clearMenus();
      },
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({
        token: state.token,
        userInfo: state.userInfo,
        isAuthenticated: state.isAuthenticated,
        permissions: state.permissions,
      }),
    }
  )
);

